<?php
/*
+--------------------------------------------------------------------------
|   Web: http://www.enbac.com 
|   Started date : 30/06/2008
+---------------------------------------------------------------------------
|   > Script written by Nova
+---------------------------------------------------------------------------
*/

if (eregi(basename( __FILE__ ), $_SERVER['PHP_SELF'])) {
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit;
}

class ajax_user {
	function playme(){
		$code = AZLib::getParam('code');

		switch( $code ){
			case 'user_info':
				$this->get_user_info();
				break;	
			case 'update':
				$this->edit_user_info();
				break;	
			case 'trans':
				$this->transaction();
				break;
			case 'login_user':
				$this->login_user();
				break;				
			case 'register':
				$this->check_exist_user();
				break;
			case 'captcha_register':
				$this->fn_captcha_register();
				break;					
			case 'password':
				$this->check_password();
				break;	
			case 'forgot_password':
				$this->forgot_password();
				break;			
			case 'remove_email_alert':
				$this->fn_remove_email_alert();
				break;	
			case 'del_openid':
				$this->del_openid();
				break;	
			case 'check_online':
				$this->check_online();
				break;
			case 'get_trans_notify_bar':
				$this->get_trans_notify_bar();
				break;
			case 'get_feed_notify_bar':
				$this->get_feed_notify_bar();
				break;
			case 'check_feed_notify_bar':
				$this->check_feed_notify_bar();
				break;
			case 'get_admin_note_notify_bar':
				$this->get_admin_note_notify_bar();
				break;
			case 'choice_service':
				$this->choice_service();
				break;
			case 'calculate_price':
				$this->calculate_price();
				break;
			case 'check_register_service':
				$this->check_register_service();
				break;
			case 'register_service':
				$this->register_service();
				break;
			case 'check_exist_acc':
				$this->check_exist_acc();
				break;
			case 'delete_register_service':
				$this->delete_register_service();
				break;
			case 'register_service_exten':
				$this->register_service_exten();
				break;
			case 'edit_exten':
				$this->edit_exten();
				break;
			case 'delete_exten':
				$this->delete_exten();
				break;
			case 'get_user_info_scs':
				$this->get_user_info_scs();
				break;
			default:
				$this->home();
				break;
		}
}

    function home(){
        global $display;
        die("Nothing to do...");
    }

    function fn_captcha_register(){
        if(User::checkLock4Ever(1)){
            echo "false";
            exit;
        }
        $captcha_register = AZLib::getParam('captcha_register');

        if(isset($_SESSION["enbac_validate"]) && $captcha_register!='' && $captcha_register == $_SESSION["enbac_validate"]){
            echo "true";
            exit;
        }
        else{
            echo "false";
            exit;
        }
    }

    function get_user_info(){
        global $display;

        $user_id  	= AZLib::getParam('user_id');
        $info  		= AZLib::getParam('id');

        $info_array =  array('blast','address','mobile_phone','home_phone','yahoo_id','skype_id','email','website','signature','up_item');

        if(!in_array($info,$info_array)){
            die("no_info");
        }

        if($user_id && (User::have_permit(ADMIN_USER) ||  (User::id() == $user_id && !User::is_block()))){
            $sql = "SELECT $info FROM user WHERE id='$user_id'";
            DB::query($sql);
            $row = DB::fetch_row();
            echo str_replace('&#33;','!',$row["$info"]);
        }
        else{
            die("no_perm");
        }
    }

    function edit_user_info()
    {
        $user_id	= (int)Url::get('user_id',0);
        $info  		= AZLib::getParam('id');
        $value  	= AZLib::getParam('value');
        $input      = array();
        $output 	= '';

        if($user_id && (User::have_permit(ADMIN_USER) ||  (User::id() == $user_id && !User::is_block())))
        {
            if($info == 'up_item')//Sửa số lượt up tin
            {
            	
            	if(User::is_admin())
            	{
                    $user 	= DB::select('user',"id=$user_id");
                    
                    if(User::is_root())//(Chỉ root đc làm ở đây!)
            		{
	                    $value = (int)$value;
	                    $input = array('up_item'=>($value>0?$value:0));
	                    $output = '<b>'.$value.'</b>';
	                    echo $output;
	                    
	                    
	                    $admin 	= User::$current->data;
	                    
	                    if($user)
	                    {
	                        $up_count 	= $value - $user['up_item'];
	
	                        if($up_count!=0){
	                        	//type: 0:Tiền mặt; 1:thu tại nhà; 2:chuyển khoản; 3:Free, KM; 8:Online
	                        	
	                            $up_log_sql = "INSERT INTO up_log (`user_id`,	`user_name`,			`admin_id`,		`admin_name`,			`time`,	 `up_count`,`up_before`,		`up_after`,	`price`,	`type`,		`note`)
	                                                VALUES ({$user['id']},	'{$user['user_name']}',{$admin['id']},	'{$admin['user_name']}',".TIME_NOW.",$up_count,'{$user['up_item']}',$value,		0,			3,			'')";
	
	                            DB::query($up_log_sql);
	
	                            if($up_count>0){
	                                $update = DB::query('UPDATE user SET up_item=up_item + '.$up_count.' WHERE id='.$user_id);
	                            }
	                            else{
	                                $update = DB::query('UPDATE user SET up_item=up_item - '.abs($up_count).' WHERE id='.$user_id);
	                            }
	
	                            //DB::Update('user',$input,"id=$user_id");
	                            User::getUser($user_id,0,1);
	                        }
	                    }
                    }
                    else
                    {
                    	$output = "<b>".(int)$user['up_item']."</b>";
	                    echo $output;
                    }
                    
                    exit;
                }
                else{
                	$output = '<b>'.$value.'</b>';
                    echo $output;
                	exit;
                }
            }
            elseif(!AZLib::checkBadWord($value) || User::have_permit(ADMIN_USER)){
                $output = 'Ch&#7913;c n&#259;ng n&#224;y &#273;ang &#273;&#432;&#7907;c b&#7893; sung. &#7844;n F5 &#273;&#7875; t&#7843;i l&#7841;i trang.';

                if($info == 'blast'){
                    $input 		= array('blast'=>$value);
                    $userblast 	= ' '.AZLib::BBCode(AZLib::cleanHtml($value));

                    if(strpos($userblast,'http://')){
                        $user_blast = $userblast;
                        while(strpos($user_blast,'http://')){
                            $tmp = substr($user_blast,strpos($user_blast,'http://'));
                            if(strpos($tmp,' ') || strpos($tmp,'<')){
                                if(strpos($tmp,' ') && strpos($tmp,'<') && (strpos($tmp,' ') > strpos($tmp,'<'))){
                                    $blast_url = substr($tmp,0,strpos($tmp,'<'));
                                }
                                else{
                                    $blast_url = substr($tmp,0,strpos($tmp,' '));
                                }
                            }
                            else{
                                $blast_url = $tmp;
                            }
                            $user_blast = str_replace($blast_url,'',$user_blast);
                        }
                        $new_blast_url = ' <a href="'.$blast_url.'" target="_blank">Click here</a>';
                        $userblast = substr($user_blast.$new_blast_url,1);
                    }

                    $user 	= User::getUser($user_id);


                    if($value){//blast không trống
                        if($value!=$user['blast']){//Thay đổi blast
                            DB::delete("feed","user_id=$user_id AND type = 8");

                            //thêm vào feed cho các thành viên theo đuôi
                            DB::query("INSERT INTO 	feed 	(type, 	user_id,  act_user_id,  time)
                                                    VALUES	(8,		$user_id, $user_id, ".TIME_NOW.")");
                        }
                    }
                    else{//Xoá blast
                        DB::delete("feed","user_id=$user_id AND type = 8");
                    }

                    $output = $userblast.' <img src="style/images/icon/icon_edit.gif" title="Click để sửa..." alt="Click để sửa..." class="hand_point" rel="blast" align="absmiddle">';
                }
                elseif($info == 'address'){
                    $input = array('address'=>trim($value));
                    $output = AZLib::word_limit($value,12,'');
                }
                elseif($info == 'mobile_phone')
                {

                    $value = preg_replace("/[^0-9]/", "", $value);

                    if(!AZLib::is_mobile($value)){
                        $value = '';
                    }

                    $input = array('mobile_phone'=>trim($value));
                    $output = AZLib::word_limit($value,10,'');

                }
                elseif($info == 'home_phone'){

                    if(User::have_permit(ADMIN_USER) || User::$current->data['phone_verify']==0){
                        $value = preg_replace("/[^0-9]/", "", $value);

                        if(AZLib::is_mobile($value) || substr($value,0,1)!="0"){
                            $value = '';
                        }

                        $input = array('home_phone'=>trim($value));
                        $output = AZLib::word_limit($value,10,'');
                    }
                }
                elseif($info == 'yahoo_id'){
                    $input = array('yahoo_id'=>trim($value));
                    $output = AZLib::word_limit($value,12,'');
                }
                elseif($info == 'skype_id'){
                    $input = array('skype_id'=>trim($value));
                    $output = AZLib::word_limit($value,12,'');
                }
                elseif($info == 'website'){
                    $input = array('website'=>trim($value));
                    $website = $value;
                    if($website!=''){
                        if(strrpos($website,'ttp://')!=1){
                            $website = 'http://'.$website;
                        }

                        if(strlen($website) > 8){
                            if(strpos($website,'/',8)>0){
                                $website = substr($website,0,strpos($website,'/',8));
                            }
                        }
                    }
                    $website = '<a href="'.$value.'" target="_blank" class="lineHeight18"><strong>'.AZLib::strippedLink($website,26).'</strong></a>';
                    $output = $website;
                }
                elseif($info == 'email' && User::is_admin()){
                    $input = array('email'=>trim($value));
                    $output = $value;
                }
                elseif($info == 'signature'){
                    $input 	= array('signature'=>trim($value));
                    $output = AZLib::parseBBCode(AZLib::cleanHtml($value));
                }
                else{
                    $output = '';
                }

                echo $output;
            }
            else{
                echo 'N&#7897;i dung c&#243; t&#7915; x&#7845;u! Click &#273;&#7875; s&#7917;a nhanh.';
                exit;
            }
        }
        else{
            echo('B&#7841;n kh&#244;ng c&#243; quy&#7873;n s&#7917;a th&#244;ng tin th&#224;nh vi&#234;n');
            exit;
        }

        if($input){
            DB::Update('user',$input,"id=$user_id");
            User::getUser($user_id,0,1);
        }
        exit;
    }

    function login_user(){
        $user_name = trim(AZLib::getParam('user'));
        $pass = Url::get('pass');

        // check de ban IP
        $ip = AZLib::ip();
        $arr_badwords = AZLib::checkBadWord($ip,true);
        if($arr_badwords["bad"]!="" && $arr_badwords["bad_key"]!=""){
            echo "unsuccess";
            exit();
        }
        // end check de ban IP

        if (strlen($user_name) <3  || strlen($user_name) >50  || preg_match('/[^A-Za-z0-9_]/',$user_name) || strlen($pass)<6){
            echo 'nodata';
            exit;
        }

        $user=str_replace(array('"','\\'),'_',$user_name);
        $user_data=DB::fetch('SELECT id,password,is_active,block_time FROM user WHERE user_name="'.$user.'"');
        if(!USER_ACTIVE_ON  && $user_data && $user_data['is_active']){
            DB::query("UPDATE user SET is_active=0 WHERE id=".$user_data['id']);
            DB::delete('user_active','user_id='.$user_data['id']);
            User::getUser($user_data['id'],0,1);
        }
        if($user_data['block_time']==-1){
            echo('unsuccess');
            exit;
        }
        elseif($user_data && $user_data['password'] == User::encode_password($pass)){
            if(USER_ACTIVE_ON && $user_data['is_active']){//Chưa kích hoạt
                echo('un_active');
            }
            else{
                if($user_data['block_time'] > TIME_NOW || $user_data['block_time']==-1){//Bị khóa hoặc khóa vĩnh viễn
                    $alert='';
                    $user_lock=DB::select('user_lock','user_id='.$user_data['id'].' AND type IN(0,1,3) ORDER BY id DESC');
                    if($user_lock){
                        if($user_lock['type']==1){//Khoá vĩnh viễn
                            User::LogOut();
                            DB::delete(_SESS_TABLE,'user_id='.$user_id,__LINE__.__FILE__);
                            exit;
                        }
                        elseif($user_lock['type']==3){//Khoá vĩnh viễn + cookie
                            User::lock4Ever(true,$user_data['id']);
                            exit;
                        }
                        else{
                            if($user_lock['note'])
                            $user_lock['note']="\n".'Lý do:"'.str_replace(array('"',"'"),'',$user_lock['note']).'"';

                            $alert='Tài khoản của bạn đang tạm khoá tới '.date('H:i, d/m/Y',$user_data['block_time']).'!'.$user_lock['note'];
                        }
                    }
                    $_SESSION['user_lock']=true;
                }

                if(Url::get('set_cookie')=='on'){
                    $year = 60 * 60 * 24 * 365 + TIME_NOW;
                    AZLib::my_setcookie("az_id", $user_data['id'], $year);
                    AZLib::my_setcookie("password", $user_data['password'], $year);
                }
                $_SESSION['is_load_page_first'] = 1;// dung jQueryUI de load bang thong bao
                
                User::LogIn($user_data['id']);

                if(isset($_SESSION['user_lock']) && $_SESSION['user_lock']){
                    echo $alert;
                    exit;
                }
                else{
                    echo('success');
                }
            }
        }
        else{
            echo('unsuccess');
            exit;
        }
        exit ();
    }

    function transaction(){// viet luu but
        header("Content-type: application/xml");

        if(!User::is_login()){
            echo "<comments><content>no_login</content></comments>";
            exit;
        }
        else{

            if(User::is_block())
            {
                echo "<comments><content>no_perm</content></comments>";
                exit;
            }


            if(AZLib::isBlackList(User::$current->data['id'],AZLib::getParam('user_id'))){
                echo "<comments><content>blacklist</content></comments>";
                exit;
            }

            if(AZLib::checkBadWord(AZLib::getParam('content'))){
                echo "<comments><content>bad_word</content></comments>";
                exit;
            }
            $user_id  = AZLib::getParam('user_id');
            if(!$user = User::getUser($user_id))
            {
                echo "<comments><content>no_perm</content></comments>";
                exit;
            }

            $content = preg_replace( "/\n/", "<br />", Url::get('content'));
            $content = str_replace('<br /><br />','&nbsp;',$content);


            $comment_content = $content;
            $id=DB::insert('comment_user',array(
                    'content'			=>$comment_content,
                    'time'				=>TIME_NOW,
                    'post_ip'			=>AZLib::ip(),
                    'sender_user_id'	=>User::id(),
                    'sender_user_name'	=>User::user_name(),
                    'receiver_user_id'	=>$user['id'],
                    'receiver_user_name'=>$user['user_name'],
                    'is_read'=>0
            ));

            if($id){
                DB::query('UPDATE user set total_comment_user=total_comment_user+1 WHERE id='.$user['id']);// so luu but
                User::getUser($user['id'],0,1);

                if($user['email'] && $user['email_alert'] && $user['id']!=User::id()){
                    //Add to cron job:
                    $link = WEB_ROOT.AZRewrite::formatUrl('?page=shop&user_name='.$user['user_name'].'&mode=comment');

                    AZLib::addCronJob('user_comment',AZLib::parseBBCode($comment_content,true),$user['id'],User::user_name(),'',0,'',$link);
                }
            }
            $time = $up_time = date('H:i | ');
            $xml = "<comments><content><![CDATA[".AZLib::parseBBCode($comment_content)."]]></content><post_time>$time</post_time></comments>";
            echo $xml;
            System::halt();
        }
    }

    function check_exist_user(){

        if(user::checkLock4Ever(1)){
            echo "false";
            exit;
        }

        if(isset($_REQUEST['register_user_name']))
        {
            $username = trim($_REQUEST['register_user_name']);

            if (!preg_match('/^[a-zA-Z0-9\_]+$/', $username))
             {
               $resp = 'false';
             }
             else
             {
                  $sql = "select id from user where user_name = '".$username."'";
                  DB::query($sql);
                  if(DB::num_rows())
                    {
                        $resp = 'false';
                    }
                  else
                    {
                        $resp = 'true';
                    }
             }

            echo $resp;
            exit;
        }
        elseif(isset($_REQUEST['email']))
        {
            $email = trim($_REQUEST['email']);

            $sql = "SELECT id FROM user WHERE email = '".$email."'";
            DB::query($sql);
            if(DB::num_rows())
             {
                $resp = 'false';
                echo $resp;
                exit;
             }
            else
             {
                $resp = 'true';
                echo $resp;
                exit;
             }

        }
    }

    function check_password()
    {
        if(isset($_REQUEST['old_password']) && User::is_login())
        {
            $password = $_REQUEST['old_password'];
            $sql = "select id from user where password = '".User::encode_password($password)."' and id='".User::$current->data['id']."'";
            DB::query($sql);
            if(DB::num_rows())
             {
                $resp = 'true';
             }
            else
             {
                $resp = 'false';
             }

            echo $resp;
            exit;
        }
        else
        {
            echo "no_login";
            exit;
        }
    }

    function forgot_password()
    {
        $email = Url::get("email","");
        $captcha_register = AZLib::getParam('captcha_register');
        $str_error = "";

        if($email && $captcha_register){

            $sql = "SELECT id FROM user WHERE email = '$email'";
            DB::query($sql);

            if(!DB::num_rows()){
                $str_error .= "<div>Email này không tồn tại</div>";
            }

            if(!isset($_SESSION["enbac_validate"]) || $captcha_register=='' || $captcha_register != $_SESSION["enbac_validate"]){
                $str_error .= "<div>Mã bảo mật không đúng</div>";
            }

            if(!$str_error){
                if($row=DB::fetch("SELECT id,user_name,email FROM user WHERE email ='$email'")){

                    $id 	= $row['id'];
                    $user 	= $row['user_name'];
                    $email 	= $row['email'];

                    $link1 = '<a href="'.WEB_ROOT.AZRewrite::formatUrl('?page=forgot_password&u='.md5($user.$email).'&id='.$id).'"><b>Khôi phục Mật khẩu</b></a>';
                    $link2 = '<a href="'.WEB_ROOT.AZRewrite::formatUrl('?page=forgot_password&u='.md5($user.$email).'&id='.$id).'"><b>Khoi phuc Mat khau</b></a>';

                    $message = file_get_contents('templates/ForgotPassword/messenger.html');

                    $message = str_replace('[[|link1|]]',$link1,$message);
                    $message = str_replace('[[|link2|]]',$link2,$message);
                    $message = str_replace('[[|user|]]',$user,$message);

                    if(System::sendEBEmail($email,'Khôi phục mật khẩu!',$message)){
                        $str_error = "";
                    }
                    else{
                        $str_error .= "<div>Email chưa được gửi đi. Hãy thử lại lần nữa</div>";
                    }
                }
            }

        }
        else{
            $str_error = "<div>Có lỗi xẩy ra. Không thực hiện được</div>";
        }

        echo $str_error;
        exit();
    }

    function fn_remove_email_alert(){
        $user_id 	 = (int)Url::get('user_id');
        $active_code = Url::get('active_code');

        if(!$user_id || !$active_code){
            echo "unsuccess";
            exit;
        }

        $arrUserCurrent = User::getUser($user_id);
        $time_del = TIME_NOW-24*3600;
        if(md5($arrUserCurrent["id"].$arrUserCurrent["password"].$arrUserCurrent["user_name"]) == $active_code){

            $id1 = DB::query('UPDATE user SET email_alert=0 WHERE  id='.$user_id);
            $id2 = DB::query('DELETE cron_job WHERE  user_id="'.$user_id.'"');

            User::getUser($user_id,0,1);

            if($id1 && $id2){
                echo Url::get('user_id');
                exit;
            }
            else{
                echo "unsuccess";
                exit;
            }
        }
        else{
            echo "unsuccess";
            exit;
        }
    }

    function del_openid(){
        $o_id = (int)Url::get('o_id',0);
        if(!User::is_login()){
            echo "not_login";
            exit;
        }

        if(User::checkLock4Ever(1) || !$o_id){
            echo "no_perm";
            exit;
        }
        else{
            $openid=DB::select("openid",'id='.$o_id." AND user_id=".User::id());
            if($openid){
                DB::delete('openid','id='.$o_id);
                echo "success";
            }
            else{
                echo "invalid";
                exit;
            }
        }
    }

  	function fn_invalid_user(){
		if(!User::is_login() || !User::have_permit(array(ADMIN_USER,MOD_VALID_USER))){
			echo "no_perm";
			exit;
		}
		
		$user_id 	= (int)Url::get('user_id',0);
		$invalid_time = (int)Url::get('invalid_time',0);
		$date_invalid 	= (int)Url::get('date_invalid',0);
		$type_invalid 	= (int)Url::get('type_invalid',0);
		$reason_invalid = AZLib::getParam('reason_invalid','');
		$reason_invalid = ($reason_invalid) ? $reason_invalid : 'Không nhập lý do kiểm duyệt' ;
		$user = User::getUser($user_id);
		
		
		
		
		if (($user['invalid_time'] > 0) || ($user['invalid_time'] == -1)){
			if(DB::update('user',array('invalid_time'=>"0"),'id ='.$user_id)){
				$sql_select_reason = 'SELECT id,admin_name,time FROM user_lock WHERE user_id = '.$user_id.' AND type = 2 ORDER BY id DESC LIMIT 1';
				$user_invalid = DB::fetch($sql_select_reason);
				
				if(MEMCACHE_ON){
					$sql 	= "SELECT * FROM item	
							   WHERE user_id = $user_id AND status = 2 AND valid_time = {$user_invalid['time']} AND modify_time_user = 0 AND valid_user ='{$user_invalid['admin_name']}'";
					$re 	= DB::query($sql);
					
					while($item_memcache = mysql_fetch_assoc($re)){
						$item_memcache['status'] 			= 1;
						$item_memcache['valid_time'] 		= TIME_NOW;
						$item_memcache['valid_user'] 	= User::user_name();
						AZMemcache::do_put("item:".$item_memcache['id'],$item_memcache);
					}
				}
				if(User::have_permit(array(ADMIN_USER))){ // chi admin quyen User moi duoc mo kiem duyet thanh vien
					DB::update('item',array('status'=>1,'valid_time'=>TIME_NOW,'valid_user'=>User::user_name()),'user_id = '.$user_id.' AND status = 2 AND valid_time = '.$user_invalid['time'].' AND modify_time_user = 0 AND valid_user ="'.$user_invalid['admin_name'].'"');
					DB::update('user_lock',array('unlock_time'=>TIME_NOW,'unlock_user'=>User::user_name()),'id = '.$user_invalid['id']);
				}
				User::getUser($user_id,1,0); // update lai cache user
				echo $user['id'];
				exit;
			}
		}
		elseif ($user['invalid_time'] == 0){
			if($type_invalid==1 && $date_invalid){
				//$timeInvalid = TIME_NOW+($date_invalid*3600*24);
				$time_start = mktime(24,0,0,date('m'),date('d'),date('Y'));
				$timeInvalid = $time_start+$date_invalid*24*3600;	
			}
			elseif($type_invalid == 2)
			{
				$timeInvalid = -1;
			}
			else
			{
				echo 'fail_valid';
				exit;
			}
			if(DB::update('user',array('invalid_time'=>$timeInvalid),'id ='.$user_id)){
				
				$user=DB::fetch('SELECT id,user_name FROM user WHERE id  = '.$user_id);
					
				if($user){
					DB::insert('user_lock',array('time'=>TIME_NOW,'time_expire'=>$timeInvalid,'user_id'=>$user['id'],'user_name'=>$user['user_name'],'type'=>2,'note'=>$reason_invalid,'admin_id'=>User::id(),'admin_name'=>User::user_name()));
				}
				$sql_item = 'SELECT id FROM item where user_id = '.$user_id.' AND status = 1';
				$re_item=DB::query($sql_item);	
				while ($item=mysql_fetch_assoc($re_item)){
					$reason = "KDTV : $reason_invalid";
					$sql_insert = "INSERT INTO bad_content (`type`,`id_item`,`user_id`,`user_name`,`reason`,`time_post`) VALUES (2,{$item['id']},".User::id().",'".User::user_name()."','".$reason."',".TIME_NOW.")";
					DB::query($sql_insert);	
				}
				
				if(MEMCACHE_ON){
					$sql 	= "SELECT * FROM item	
							   WHERE user_id = $user_id AND status = 1";
					$re 	= DB::query($sql);
					
					while($item_memcache = mysql_fetch_assoc($re)){
						$item_memcache['status'] 			= 2;
						$item_memcache['valid_time'] 		= TIME_NOW;
						$item_memcache['valid_user'] 	= User::user_name();
						AZMemcache::do_put("item:".$item_memcache['id'],$item_memcache);
					}
				}
				
				$receiver_user 		=  User::getUser($user_id);
				
				$title_pm = 'Thông báo kiểm duyệt thành viên từ EnBac';
				$content_pm = 'Bạn đã bị kiểm duyệt với lý do: '.$reason.'
				
				Tất cả các tin đăng của bạn cũng sẽ bị kiểm duyệt.
				
				Đề nghị bạn hãy thực hiện đúng các quy định của Én Bạc.
				
				Xin cảm ơn bạn.
				
				Vui lòng không trả lời tin nhắn này!';								
				
				AZLib::Send_pm(User::id(), User::user_name(), $receiver_user, $title_pm, $content_pm,true);											
				
				DB::update('item',array('status'=>"2",'valid_time'=>TIME_NOW,'valid_user'=>User::user_name()),'user_id = '.$user_id.' AND status = 1');
				User::getUser($user_id,1,0); // update lai cache user
				echo $user['id'];
				exit;
			}
		}else{
			echo 'fail_valid';
			exit;
		}
	}
	
	function check_online(){
		$user_id =	(int)Url::get('user_id');
		
		if($user_id){
			$json = '';
		
			$sql="SELECT user_id, user_name, session_expires FROM "._SESS_TABLE." WHERE user_id=$user_id ORDER BY session_expires DESC LIMIT 1";
			
			$re=DB::query($sql);								
			if($re){
				
				$user = mysql_fetch_assoc($re);
				if($user && $user['session_expires']>( TIME_NOW - 900 )){
					echo 1;
					exit;
				}
			}
		}
		echo 0;
		exit;
	}
	
	function get_trans_notify_bar(){
		AZLib::getCats();
		$json 		= "";
		if(!User::is_login()){
			$json = '({"msg":"no_login"})';
			echo $json;
			exit;
		}
		if(User::is_login()){
			AZLib::getCats();
			
			//Notify bar
			// danh sach giao dich
			$select = 'SELECT id, name, category_id, level_1_catid, img_url, read_count, up_time, img_server FROM item WHERE status = 1 AND user_id='.User::id().' ORDER BY shop_order, up_time DESC LIMIT 0,50';
			$re = DB::query($select);
			$items = array();
			
			if($re){
				$json  = ''; 
				while ($item = mysql_fetch_assoc($re)){
					$ebname = AZLib::safe_title($item['name']);
					if(isset(CGlobal::$allCategories[$item['level_1_catid']])){						
						$cat_name = CGlobal::$allCategories[$item['level_1_catid']]['name'];														
						$item['href'] =  WEB_DIR.AZLib::safe_title($cat_name)."/p{$item['id']}/$ebname.html";						
					}
					else{							
						$item['href'] =  WEB_DIR."/p{$item['id']}/$ebname.html";
					}
					if ($item['img_url']){
						$item['img_url'] = AZLib::getImageThumb($item['img_url'],60,0,1,$item['img_server']);
					}
					else{
						$item['img_url'] = 'style/images/no-images-69x53.jpg';
					}					
					$item['up_time']	  = 	date('H:i | d-m-Y',$item['up_time']);
					
					$json  .= '{"id":"'.$item['id'].'","read_count":"'.$item['read_count'].'","time":"'.$item['up_time'].'","name":"'.$item['name'].'","link":"'.$item['href'].'","images":"'.$item['img_url'].'"},';
				}
                if ($json){
                    $json = '['.substr($json,0,-1).']';
                }
                else{
                    $json = '({"msg":"no_trans"})';
                }
			}
			
			echo $json;
			exit;
		}
	}
	
	function get_feed_notify_bar(){	
		AZLib::getCats();	
		$json 		= "";
		if(!User::is_login()){
			$json = '({"msg":"no_login"})';
			echo $json;
			exit;
		}
											
		$item_comment_ids 	= "";//Id các phản hồi giao dịch
		$user_comment_ids 	= "";//Id các lưu bút
		$entry_comment_ids 	= "";//Id các bài viết			
		/*$follow_ids			= "";//Id các theo đuôi*/
		$blast_user_ids			="";// Id các balst
		
		$arr_data = array();	
		
		$user = User::getUser(User::id());
		
		if($user["total_pm"]){ // neu co PM moi
			$arr_data = array("new_pm"=>$user["total_pm"]);
		}
					
		$where = "WHERE user_id = ".User::id();
		$limit = " LIMIT 20";
		
		$sql = "SELECT * FROM feed $where ORDER BY time DESC $limit";		
		$re = DB::query($sql);
		
		if($re){	
			while($feed = mysql_fetch_assoc($re)){
				if($feed['type']==1 || $feed['type']==2){ // phan hoi
					$item_comment_ids.=($item_comment_ids!=''?',':'').$feed['ref_id'];						
				}
				elseif($feed['type']==3){// luu but
					$user_comment_ids.=($user_comment_ids!=''?',':'').$feed['ref_id'];
				}					
				elseif($feed['type']==5 || $feed['type']==6){// bai viet
					$entry_comment_ids.=($entry_comment_ids!=''?',':'').$feed['ref_id'];
				}
				/*elseif($feed['type']==7){// theo duoi						
					$follow_ids.=($follow_ids!=''?',':'').$feed['ref_id'];
				}*/																						
			}
		}
		
		//Phản hồi giao dịch
		$item_comment_arr = array();
		if($item_comment_ids!=''){
			$item_ids = "";
			$re = DB::query("SELECT time, item_id, parent_id, COUNT(item_id) AS total_comment FROM comment WHERE id IN($item_comment_ids) GROUP BY item_id");
			if($re){
				while ($comment = mysql_fetch_assoc($re)){
					$item_ids.=($item_ids!=''?',':'').$comment['item_id'];						
					$comment['time'] = AZLib::duration_time($comment['time']);												
					$item_comment_arr[$comment['item_id']] = $comment;
				}
				
				if($item_comment_arr && $item_ids){ // Query de lay ID va Tieu de tin
					$re = DB::query("SELECT id, name, level_1_catid FROM item WHERE id IN($item_ids)");
					while($item = mysql_fetch_assoc($re)){
						if($item["id"] == $item_comment_arr[$item["id"]]["item_id"]){
							$item_comment_arr[$item["id"]]["item_name"] = AZLib::word_limit($item["name"],7,'...');														
							$ebname = AZLib::safe_title($item['name']);							
							if(isset(CGlobal::$allCategories[$item['level_1_catid']])){																											
								$cat_name = CGlobal::$allCategories[$item['level_1_catid']]['name'];	
								$item_comment_arr[$item["id"]]["url_link"] =  WEB_DIR.AZLib::safe_title($cat_name)."/p{$item['id']}/$ebname.html";							
							}
							else{							
								$item_comment_arr[$item["id"]]["url_link"] =  WEB_DIR."/p{$item['id']}/$ebname.html";	
							}																				
						}
					}
				}
			}
			
			if($item_comment_arr){
				$item_comment_arrs["comment"] = $item_comment_arr;
				$arr_data += $item_comment_arrs;
			}				
		}																		
		// End Phan hoi giao dich
		
		//Luu but
		$total_comment_arr = array();
		if($user_comment_ids!=''){
			$re = DB::query("SELECT time, COUNT(id) AS total_comment_user FROM comment_user WHERE id IN($user_comment_ids) GROUP BY receiver_user_id ORDER BY time DESC");
			if($re){
				$comment_user = mysql_fetch_assoc($re);
				$total_comment_arr["total"] = $comment_user["total_comment_user"];	
				$total_comment_arr['time'] = AZLib::duration_time($comment_user['time']);
				$total_comment_arr["url_link"] = WEB_DIR.'Shop/'.User::user_name().'/Luu-but';
			}
			
			if($total_comment_arr){
				$total_comment_arrs["comment_user"] = $total_comment_arr;
				$arr_data += $total_comment_arrs;
			}
		}
		//End Luu but
		
		// Theo duoi
		/*$follow_arr = array();
		if($follow_ids!=''){
			$re = DB::query("SELECT id, follower_name, time FROM follow WHERE id IN($follow_ids) ORDER BY time DESC");			
			if($re){				
				while ($follow = mysql_fetch_assoc($re)){										
					$follow['time'] = AZLib::duration_time($follow['time']);
					$follow["url_link"] = WEB_DIR.$follow['follower_name'];
					$follow_arr[$follow['id']] = $follow;
				}														
			}							
			if($follow_arr){
				$follow_arrs["follow"] = $follow_arr;
				$arr_data += $follow_arrs;
			}
		}*/
		// end Theo duoi
		
		// Phản hồi bài viết
		$entry_comment_arr = array();
		if($entry_comment_ids!=''){
			$entry_ids = "";
			$re = DB::query("SELECT time, entry_id, parent_id FROM user_entry_comment WHERE id IN($entry_comment_ids)");
			if($re){
				while ($comment_entry = mysql_fetch_assoc($re)){
					$entry_ids.=($entry_ids!=''?',':'').$comment_entry['entry_id'];
					$comment_entry['time'] = AZLib::duration_time($comment_entry['time']);
					$comment_entry['total_comment_entry'] = count(explode(',',$entry_comment_ids));
					$entry_comment_arr[$comment_entry['entry_id']] = $comment_entry;
					
				}
				
				if($entry_comment_arr && $entry_ids){ // Query de lay ID va Tieu de bai viet
					$re = DB::query("SELECT id, title FROM user_entry WHERE id IN($entry_ids)");
					while($entry = mysql_fetch_assoc($re)){
						if($entry["id"] == $entry_comment_arr[$entry["id"]]["entry_id"]){
							$entry_comment_arr[$entry["id"]]["title"] = AZLib::word_limit($entry["title"],7,'...');															
							$ebname = AZLib::safe_title($entry['title']);
							$entry_comment_arr[$entry["id"]]["url_link"] =  WEB_DIR."Bai-viet/".User::user_name()."/e{$entry['id']}/$ebname";								
						}
					}
				}
			}
			
			if($entry_comment_arr){
				$item_comment_arrs["entry"] = $entry_comment_arr;
				$arr_data += $item_comment_arrs;
			}				
		}																		
		// End Phan hoi bài viết
				
		$json = json_encode($arr_data);
		
		echo $json;		
		exit();
	}
	function check_feed_notify_bar(){
		if(!User::is_login()){
			$json = '({"msg":"no_login"})';
			echo $json;
			exit;
		}
		$total_pm = DB::count('feed',"user_id = ".User::id()." AND type = 4 AND is_alert = 0");
		$total_item_comment = DB::count('feed',"user_id = ".User::id()." AND type IN(1,2) AND is_alert = 0");
		$total_user_comment = DB::count('feed',"user_id = ".User::id()." AND type = 3 AND is_alert = 0");
		$total_entry_comment = DB::count('feed',"user_id = ".User::id()." AND type IN (5,6) AND is_alert = 0");
		
		
		$json_content = array();
		
		$json_content['total_pm'] 	    	    = ($total_pm) ? (int)$total_pm : 0;
		$json_content['total_item_comment'] 	    = ($total_item_comment) ? (int)$total_item_comment : 0;
		$json_content['total_user_comment'] 	    = ($total_user_comment) ? (int)$total_user_comment : 0;
		$json_content['total_entry_comment'] 	    = ($total_entry_comment) ? (int)$total_entry_comment : 0;
		
		// check xem co thong bao moi tu BQT hay ko
		$have_admin_notice = 0;
		if(isset($_COOKIE['have_admin_notice'])){
			$arr_have_admin_notice = explode(",",$_COOKIE['have_admin_notice']);
			$arr_data = User::getAdminNotice();						
			foreach($arr_data as $value){				
				if(!in_array($value["id"], $arr_have_admin_notice)){
					$have_admin_notice = 1;
				}
			}
		}
		else{			
			$have_admin_notice = 1;
		}
		$json_content['admin_notice'] = $have_admin_notice;
		// End check xem co thong bao moi tu BQT hay ko
		
		$json = json_encode($json_content);
		
		echo $json;
				
		if($total_pm){
			DB::update('feed',array('is_alert'=>1),"user_id = ".User::id()." AND type = 4 AND is_alert = 0");
		}
		if($total_item_comment){
			DB::update('feed',array('is_alert'=>1),"user_id = ".User::id()." AND type IN(1,2) AND is_alert = 0");
		}
		if($total_user_comment){
			DB::update('feed',array('is_alert'=>1),"user_id = ".User::id()." AND type = 3 AND is_alert = 0");
		}
		if($total_entry_comment){
			DB::update('feed',array('is_alert'=>1),"user_id = ".User::id()." AND type IN (5,6) AND is_alert = 0");
		}
		
		exit();					
	}
	
	function get_admin_note_notify_bar(){
	
		$arr_data = array();	
		$json 		= "";
		
		if(!User::is_login()){
			$json = '({"msg":"no_login"})';
			echo $json;
			exit;
		}
				
		$arr_data_tmp = User::getAdminNotice();			
		foreach($arr_data_tmp as $value){
			$arr_data[$value["id"]] = $value;
		}
			
		if(!$arr_data){
			$arr_data = array("msg"=>"empty");
		}
		
		$json = json_encode($arr_data);
		
		echo $json;		
		exit();			
	}

    function choice_service(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}

        $group_service = (int)AZLib::getParam('group_service');
        $sql = "SELECT SG.service_name, S.type_name, S.count, SG.price
                FROM services_group AS SG
                LEFT JOIN services AS S
                ON S.type_name = 'up_".$group_service."' OR S.type_name = 'cpc_".$group_service."' OR S.type_name = 'item_".$group_service."'
                WHERE SG.id = ".$group_service."";

        $aryServiceInfo = DB::fetch_all($sql);
        $json = json_encode($aryServiceInfo);
        echo $json;
        exit();
    }

    function calculate_price(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}
        
        $type_service = AZLib::getParam('type_service');
        $data_cout = AZLib::getParam('data_cout');
        $total_price = AZLib::getParam('total_price');
        
        $service = 0;
        if($type_service == "up"){
            $where = " WHERE type_name = 'up_".$service."'";
        }elseif($type_service == "cpc"){
            $where = " WHERE type_name = 'cpc_".$service."'";
        }elseif($type_service == "item"){
            $where = " WHERE type_name = 'item_".$service."'";
        }
        
        $sql = "SELECT type_name, count, price
        FROM services".$where;
        
        $aryServiceInfo = DB::fetch($sql);

        if(($total_price == 0)){
            unset($_SESSION['up_count']);
            unset($_SESSION['cpc_count']);
            unset($_SESSION['item_count']);
        }
        
        if($type_service == "up"){
            if(isset ($_SESSION['up_count'])){
                $up_price = $_SESSION['up_count'];
                $total_price = $total_price - $up_price;
            }
            $_SESSION['up_count'] = ($data_cout/$aryServiceInfo['count'])*$aryServiceInfo['price'];
        }elseif($type_service == "cpc"){
            if(isset ($_SESSION['cpc_count'])){
                $cpc_price = $_SESSION['cpc_count'];
                $total_price = $total_price - $cpc_price;
            }
            $_SESSION['cpc_count'] = ($data_cout/$aryServiceInfo['count'])*$aryServiceInfo['price'];
        }elseif($type_service == "item"){
            if(isset ($_SESSION['item_count'])){
                $item_price = $_SESSION['item_count'];
                $total_price =$total_price - $item_price;
            }
            $_SESSION['item_count'] = ($data_cout/$aryServiceInfo['count'])*$aryServiceInfo['price'];
        }
        
        $total_price += ($data_cout/$aryServiceInfo['count'])*$aryServiceInfo['price'];

        echo $total_price;
    }
    
    function check_register_service(){
        $json['error'] = "";
        $json['user_group'] = 0;
        $json['id'] = 0;
        if(!User::is_login()){
			$json['error'] = "not_login";
            echo json_encode($json);
			exit();
		}

		if(User::is_block()){
            $json['error'] = "no_permission";
            echo json_encode($json);
			exit();
		}

        $user_name = User::user_name();

        //kiểm tra xem user có thuộc nhóm premium hay không.
        if(User::isPremium()){
            $json['user_group'] = 1;
        }
        //end
        
        $service_name = Url::get('service_name', '');
        $aryOrder = array();
        $aryOrder = DB::select_all('order_services', "user_use='".$user_name."' AND (active = 1 OR active = 0 OR active = -4)");

        if(count($aryOrder) > 0 && !User::is_root()){
            foreach($aryOrder as $val){
                if($service_name == $val['type_scs']){
                    $json['error'] = "exist_service_order";
                    echo json_encode($json);
                    exit();
                }
                if($val['payment_status'] == 1){
                    $json['error'] = "over_reg_scs_payment";
                }else{
                    if($val['active'] == 1){
                        $json['error'] = "over_reg_scs_active";
                    }elseif($val['active'] == -3 || $val['active'] == 0 || $val['active'] == -4){
                        $json['error'] = "confirm_cancel_reg_scs";
                        $json['id'] = $val['id'];
                    }
                }
            }
            echo json_encode($json);
            exit();
        }else{
            $json['error'] = "success";
            echo json_encode($json);
			exit();
        }
    }

    function register_service(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}
        
        $user               = User::$current->data;
        $user_name          = $user['user_name'];
        $whereOrderCheck    = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
        
        $countItemOrder     = DB::count('order_services',$whereOrderCheck);
        
        if($countItemOrder > 0 && !User::is_root())//Đã đăng ký dịch vụ rùi
        {
            echo "over_reg_scs";
            exit();
        }

        $payment_types  = (int)Url::get('payment_types');
        $type_service   = (int)Url::get('type_service');

        if($type_service <= 0 || $type_service > 5)
        {
            echo "error_service";
            exit();
        }
        else
        {
            $service = DB::select("services_group","id=$type_service");

            if(!$service || ($service && $service['price']<=0))
            {
                echo "error";
                exit;
            }
        }
       
        if($payment_types == 1)//Thông tin thanh toán
        {
        	//check submit nhieu lan
            $user_name = $user['user_name'];
            $whereOrderCheck = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
            $countItemOrder = DB::count('order_services',$whereOrderCheck);
            if($countItemOrder > 0 && !User::is_root()){
                exit();
            }
            
            //tao mang du lieu cho bang services_group
            $aryServiceGroup = DB::select('services_group', 'id='.$type_service);
            if($aryServiceGroup){
                $orderInfo = array(
                    "user_use"      => $user['user_name'],
                    "type_scs"      => $aryServiceGroup['service_name'],
                    "date_reg"      => TIME_NOW,
                    "up_count"      => $aryServiceGroup['up_count'],
                    "cpc_count"     => $aryServiceGroup['cpc_count'],
                    "item_count"    => $aryServiceGroup['item_count'],
                    "take_care"     => $aryServiceGroup['take_care'],
                    "price"         => $aryServiceGroup['price'],
                    "payment_types" => $payment_types,
                    "active"        => -4 //dang ky scs kieu thanh toan online nhung chua tra tien
                );
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }

            if($id){
                $full_name			= Url::get("full_name");
                $mobile				= Url::get("mobile");

                if(!$full_name || !$mobile)//Phải nhập tên và số điện thoại liên hệ
                {
                    echo "error";
                    exit;
                }

                $order_code         = $type_service."_".$id;
                $return_url         = WEB_ROOT."payment_scs.html?cmd=complete&order_id=$id&payment_types=1&type_service=$type_service";
                $transaction_info   = "Thanh toán DV Siêu Chăm Sóc {$service['service_name']} cho $full_name [ {$user['user_name']} ], số ĐT liên hệ: $mobile";
                $order_email        = $user['email'];
                $price              = (int)$service['price'];

                //insert vao payment_scs
                $pay_info = $full_name.",".$user['email'].",".$mobile.",".$service['service_name'];

                $paymentInfo = array(
                    "order_service_id"  => $id,
                    "user_id"           => $user['id'],
                    "user_name"         => $user['user_name'],
                    "payment_types"     => $payment_types,
                    "payment_type_soha" => 0,
                    "payment_info"      => $pay_info,
                    "order_code"        => $order_code,
                    "price"             => $price,
                    "time"              => time(),
                    "error_text"        => "Đang chờ thanh toán",
                    "payment_status"    => -1
                );

                //insert
                DB::insert('payment_scs', $paymentInfo);
                //end

                //Tạo link thanh toán đến Soha Payment
                $url= SohaPay::buildCheckoutUrl($return_url, $transaction_info, $order_code, $price, $order_email,SCS_MERCHANT_SITE_CODE,SCS_SECURE_CODE);
                echo $url;
                exit();
            }else{
                echo "error_connect";
                exit;
            }
        }
        else if($payment_types == 2)
        {
            global $display;
            //check submit nhieu lan
            $user_name = $user['user_name'];
            $whereOrderCheck = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
            $countItemOrder = DB::count('order_services',$whereOrderCheck);
            if($countItemOrder > 0 && !User::is_root()){
                exit();
            }
            
            //tao mang du lieu cho bang services_group
            $aryServiceGroup = DB::select('services_group', 'id='.$type_service);
            if($aryServiceGroup){
                $orderInfo = array(
                    "user_use"   => $user['user_name'],
                    "type_scs"   => $aryServiceGroup['service_name'],
                    "date_reg"   => TIME_NOW,
                    "up_count"   => $aryServiceGroup['up_count'],
                    "cpc_count"  => $aryServiceGroup['cpc_count'],
                    "item_count" => $aryServiceGroup['item_count'],
                    "take_care"  => $aryServiceGroup['take_care'],
                    "price"      => $aryServiceGroup['price'],
                    "payment_types" => $payment_types,
                    "active"     => 0
                );
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }
            
            if($id){
                $payment_info = "";
                $full_name = AZLib::getParam('ho_ten');
                $dienthoai = AZLib::getParam('dien_thoai');
                $dia_chi = AZLib::getParam('dia_chi');
                $thanh_pho = AZLib::getParam('thanh_pho');
                $ngay = AZLib::getParam('ngay');
                $time = AZLib::getParam('time');
                $payment_info .= $full_name.",".$dienthoai.",".$dia_chi.",".$thanh_pho.",".$ngay.",".$time;
            
                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);
                $display->add('full_name',$full_name);
                $display->add('dia_chi',$dia_chi);
                $display->add('thanh_pho',  SohaPay::infoForUser($thanh_pho, 'tp'));
                $display->add('ngay',$ngay);
                $display->add('time',  SohaPay::infoForUser($time, 'time'));
                $display->add('service_name', $aryServiceGroup['service_name']);
                $display->add('price', number_format($aryServiceGroup['price']));

                $content_email=$display->output('payment_online_reg_2',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Đăng ký thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho ban payment scs
                $paymentInfo = array(
                    "order_service_id" => $id,
                    "user_id"        => $user['id'],
                    "user_name"      => $user['user_name'],
                    "payment_types"  => $payment_types,
                    "payment_info"   => $payment_info,
                    "price"          => $aryServiceGroup['price'],
                    "payment_status" => 0,
                    "send_mail_stt"  => $send_mail_stt
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);
                
                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id";
                echo $url;
                exit();
            }
        }else if($payment_types == 3){
            global $display;

            //check submit nhieu lan
            $user_name = $user['user_name'];
            $whereOrderCheck = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
            $countItemOrder = DB::count('order_services',$whereOrderCheck);
            if($countItemOrder > 0 && !User::is_root()){
                exit();
            }
            
            //tao mang du lieu cho bang services_group
            $aryServiceGroup = DB::select('services_group', 'id='.$type_service);
            if($aryServiceGroup){
                $orderInfo = array(
                    "user_use"   => $user['user_name'],
                    "type_scs"   => $aryServiceGroup['service_name'],
                    "date_reg"   => TIME_NOW,
                    "up_count"   => $aryServiceGroup['up_count'],
                    "cpc_count"  => $aryServiceGroup['cpc_count'],
                    "item_count" => $aryServiceGroup['item_count'],
                    "take_care"  => $aryServiceGroup['take_care'],
                    "price"      => $aryServiceGroup['price'],
                    "payment_types" => $payment_types,
                    "active"     => 0
                );
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }
            
            if($id){
                $payment_info = "";
                if($user['mobile_phone'] ==""){
                    $phone = $user['home_phone'];
                }else{
                    $phone = $user['mobile_phone'];
                }
                $payment_info .= $user['email'].",".$phone;

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);

                $display->add('service_name', $aryServiceGroup['service_name']);
                $display->add('price', number_format($aryServiceGroup['price']));

                $content_email=$display->output('payment_online_reg_3',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Đăng ký thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho ban payment scs
                $paymentInfo = array(
                    "order_service_id" => $id,
                    "user_id"        => $user['id'],
                    "user_name"      => $user['user_name'],
                    "payment_types"   => $payment_types,
                    "payment_info"   => $payment_info,
                    "price"          => $aryServiceGroup['price'],
                    "payment_status" => 0,
                    "send_mail_stt"  =>$send_mail_stt
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);
                
                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id";
                echo $url;
                exit();
            }
        }else if($payment_types == 4){
            global $display;

            //check submit nhieu lan
            $user_name = $user['user_name'];
            $whereOrderCheck = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
            $countItemOrder = DB::count('order_services',$whereOrderCheck);
            if($countItemOrder > 0 && !User::is_root()){
                exit();
            }
            
            //tao mang du lieu cho bang services_group
            $aryServiceGroup = DB::select('services_group', 'id='.$type_service);
            if($aryServiceGroup){
                $orderInfo = array(
                    "user_use"   => $user['user_name'],
                    "type_scs"   => $aryServiceGroup['service_name'],
                    "date_reg"   => TIME_NOW,
                    "up_count"   => $aryServiceGroup['up_count'],
                    "cpc_count"  => $aryServiceGroup['cpc_count'],
                    "item_count" => $aryServiceGroup['item_count'],
                    "take_care"  => $aryServiceGroup['take_care'],
                    "price"      => $aryServiceGroup['price'],
                    "payment_types" => $payment_types,
                    "active"     => 0
                );
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }
            
            if($id){
                $banking_type = Url::get('banking_type');
                $banking_code = SohaPay::listBankCode($banking_type);
                
                $payment_info = "";
                if($user['mobile_phone'] ==""){
                    $phone = $user['home_phone'];
                }else{
                    $phone = $user['mobile_phone'];
                }
                $payment_info .= $user['email'].",".$phone.",".$banking_code;

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);

                $display->add('service_name', $aryServiceGroup['service_name']);
                $display->add('price', number_format($aryServiceGroup['price']));
                $display->add('banking_type', $banking_type);
                $display->add('accNumber', SohaPay::listAccountNumber($banking_code));
                $display->add('banking_name', SohaPay::listBanking($banking_code));
                $display->add('banking_note', SohaPay::listBanking($banking_code, true));

                $content_email=$display->output('payment_online_reg_4',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Đăng ký thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho ban payment scs
                $paymentInfo = array(
                    "order_service_id" => $id,
                    "user_id"        => $user['id'],
                    "user_name"      => $user['user_name'],
                    "payment_types"  => $payment_types,
                    "payment_info"   => $payment_info,
                    "price"          => $aryServiceGroup['price'],
                    "payment_status" => 0,
                    "send_mail_stt"  => $send_mail_stt
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);

                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id";
                echo $url;
                exit();
            }
        }else if($payment_types == 5){ //hinh thuc mua tra sau
            global $display;

            //check submit nhieu lan
            $user_name = $user['user_name'];
            $whereOrderCheck = "user_use='".$user_name."' AND (active = 1 OR active = 0)";
            $countItemOrder = DB::count('order_services',$whereOrderCheck);
            if($countItemOrder > 0 && !User::is_root()){
                exit();
            }

            //tao mang du lieu cho bang services_group
            $aryServiceGroup = DB::select('services_group', 'id='.$type_service);


            if($aryServiceGroup){

                //check xem user co the tiep tuc mua hay khong
                $user_onDB = DB::select('user',"id={$user['id']}");
                if(($user_onDB['money_quota']*1000) < (($user_onDB['money_used']*1000)+$aryServiceGroup['price'])){
                    echo "over_money";
                    exit;
                }

                //luu lai so tien da su dung
                $last_money_used = ($user_onDB['money_used'])+($aryServiceGroup['price']/1000);
                DB::update('user', array('money_used' => $last_money_used), "user_name='{$user_name}'");
                if(MEMCACHE_ON)
                {
                    $user['money_used'] = $last_money_used;
                    AZMemcache::do_put("user:{$user['id']}",$user);
                }

                $orderInfo = array(
                    "user_use"      => $user['user_name'],
                    "type_scs"      => $aryServiceGroup['service_name'],
                    "date_reg"      => TIME_NOW,
                    "up_count"      => $aryServiceGroup['up_count'],
                    "cpc_count"     => $aryServiceGroup['cpc_count'],
                    "item_count"    => $aryServiceGroup['item_count'],
                    "take_care"     => $aryServiceGroup['take_care'],
                    "price"         => $aryServiceGroup['price'],
                    "payment_types" => $payment_types,
                    "active"        => 0
                );
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }

            if($id){
                $payment_info = "";
                if($user['mobile_phone'] ==""){
                    $phone = $user['home_phone'];
                }else{
                    $phone = $user['mobile_phone'];
                }
                $payment_info .= $user['email'].",".$phone.",".$user['address'];

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);

                $display->add('service_name', $aryServiceGroup['service_name']);
                $display->add('price', number_format($aryServiceGroup['price']));

                $content_email=$display->output('payment_online_reg_5',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Đăng ký thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //insert vao bang payment_premium
                $premium_scs = array(
                    "log_id"    => $id,
                    "user_id"   => $user['id'],
                    "user_name" => $user['user_name'],
                    "type"      => 3, //scs
                    "pay_info"  => "Mua SCS gói [{$aryServiceGroup['service_name']}]",
                    "price"     => $aryServiceGroup['price'],
                    "time"      => TIME_NOW,
                    "status"    => 0
                );
                //insert
                DB::insert('payment_premium', $premium_scs);

                //tao mang du lieu cho ban payment scs
                $paymentInfo = array(
                    "order_service_id" => $id,
                    "user_id"        => $user['id'],
                    "user_name"      => $user['user_name'],
                    "payment_types"   => $payment_types,
                    "payment_info"   => $payment_info,
                    "price"          => $aryServiceGroup['price'],
                    "payment_status" => 0,
                    "send_mail_stt"  =>$send_mail_stt
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);

                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id";
                echo $url;
                exit();
            }
        }
    }

    function check_exist_acc(){
        if(user::checkLock4Ever(1)){
            echo "false";
            exit;
        }

        if(isset($_REQUEST['user_name']))
        {
            $username = trim($_REQUEST['user_name']);

            if (!preg_match('/^[a-zA-Z0-9\_]+$/', $username))
             {
               $resp = 'empty';
             }
             else
             {
                  $sql = "select id from user where user_name = '".$username."'";
                  DB::query($sql);
                  if(DB::num_rows())
                    {
                        $resp = 'success';
                    }
                  else
                    {
                        $resp = 'not_exist';
                    }
             }

            echo $resp;
            exit;
        }
    }

    function delete_register_service(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}

        $user            = User::$current->data;

        $id = (int)Url::get('service_id',0);
        $aryOrderService = array();

        if($id){
            $aryOrderService = DB::select("order_services","id=$id");
        }

        if($aryOrderService)
        {
            if($aryOrderService['active'] != -2){
                DB::update('order_services',array('active'=>-2,'time_del'=> TIME_NOW,'user_del'=> User::user_name()),"id={$aryOrderService['id']}");
                DB::update('payment_scs', array('del_status' => -1), "order_service_id={$aryOrderService['id']}");

                //tra lai so tien khong su dung cho user
                $user_onDB = DB::select('user',"id={$user['id']}");
                $last_money_used = ($user_onDB['money_used'])-($aryOrderService['price']/1000);
                DB::update('user', array('money_used' => $last_money_used), "user_name='{$user['user_name']}'");
                DB::update('payment_premium', array('status' => 2), "log_id={$aryOrderService['id']}");
                if(MEMCACHE_ON)
                {
                    $user['money_used'] = $last_money_used;
                    AZMemcache::do_put("user:{$user['id']}",$user);
                }
            }
            echo "success";
            exit();
        }
        echo "error";
        exit();
    }

    function register_service_exten(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}

        //get user
        $user               = User::$current->data;
        $user_name          = $user['user_name'];

        //Kieu thanh toan
        $payment_types  = (int)Url::get('payment_types');

        //Thong tin gia han
        $order_service_id = (int)Url::get('order_service_id',0); //id order service
        $time_exten = (int)Url::get('time_exten',0); //thoi gian gia han (thang)
        $aryOrderService = array();

        if($order_service_id){
            $aryOrderService = DB::select("order_services","id=$order_service_id");
        }

        if($aryOrderService)
        {
            //kiểm tra thông tin đầu vào
            if($aryOrderService['user_use'] != $user_name){
                echo "error";
                exit;
            }

            if($aryOrderService['active'] != 1){
                echo "error";
                exit;
            }

            $price = ($aryOrderService['price']/$aryOrderService['time_use'])*$time_exten;
        }else{
            echo "error";
            exit;
        }

        if($payment_types == 1)//Thông tin thanh toán
        {
        	$full_name			= Url::get("full_name");
        	$mobile				= Url::get("mobile");

        	if(!$full_name || !$mobile)//Phải nhập tên và số điện thoại liên hệ
            {
                echo "error";
                exit;
            }

            $price = ($aryOrderService['price']/$aryOrderService['time_use'])*$time_exten;

            $orderInfo = array(
                "user_use"              => $user_name,
                "type_scs"              => $aryOrderService['type_scs'],
                "date_reg"              => TIME_NOW,
                "up_count"              => $aryOrderService['up_count'],
                "cpc_count"             => $aryOrderService['cpc_count'],
                "item_count"            => $aryOrderService['item_count'],
                "take_care"             => $aryOrderService['take_care'],
                "price"                 => $price,
                "payment_types"         => $payment_types,
                "time_use"              => $time_exten,
                "active"                => -4,
                "reg_exten_stt"         => 1
            );

            //insert
            $id= DB::insert('order_services', $orderInfo);

            if($id){
                $order_code         = "GH_{$order_service_id}_{$id}";
                $return_url         = WEB_ROOT."payment_scs.html?cmd=complete_exten&exten_order_id=$id&payment_types=1&order_service_id=$order_service_id&time_exten=$time_exten";
                $transaction_info   = "Thanh toán DV gia hạn Siêu Chăm Sóc {$aryOrderService['type_scs']} cho $full_name [ {$user['user_name']} ], số ĐT liên hệ: $mobile";
                $order_email        = $user['email'];

                //insert payment_scs exten
                $pay_info = $full_name.",".$user['email'].",".$mobile.",".$aryOrderService['type_scs'];

                $paymentInfo = array(
                    "order_service_id"  => $id,
                    "user_id"           => $user['id'],
                    "user_name"         => $user['user_name'],
                    "payment_types"     => $payment_types,
                    "payment_type_soha" => 0,
                    "payment_info"      => $pay_info,
                    "order_code"        => $order_code,
                    "price"             => $price,
                    "time"              => time(),
                    "error_text"        => "Đang chờ thanh toán",
                    "payment_status"    => -1,
                    "reg_exten_stt"     => 1
                );

                //insert
                DB::insert('payment_scs', $paymentInfo);

                //Tạo link thanh toán đến Soha Payment
                $url= SohaPay::buildCheckoutUrl($return_url, $transaction_info, $order_code, $price, $order_email,SCS_MERCHANT_SITE_CODE,SCS_SECURE_CODE);
                echo $url;
                exit();
            }else{
                echo "error_connect";
                exit;
            }
        }
        else if($payment_types == 2)
        {
            global $display;

            if($aryOrderService){
                $orderInfo = array(
                    "user_use"              => $user_name,
                    "type_scs"              => $aryOrderService['type_scs'],
                    "date_reg"              => TIME_NOW,
                    "up_count"              => $aryOrderService['up_count'],
                    "cpc_count"             => $aryOrderService['cpc_count'],
                    "item_count"            => $aryOrderService['item_count'],
                    "take_care"             => $aryOrderService['take_care'],
                    "price"                 => $price,
                    "payment_types"         => $payment_types,
                    "time_use"              => $time_exten,
                    "active"                => -3,
                    "reg_exten_stt"         => 1
                );
                
                //insert
                $id= DB::insert('order_services', $orderInfo);
            }

            if($id){
                $payment_info = "";
                $full_name = AZLib::getParam('ho_ten');
                $dienthoai = AZLib::getParam('dien_thoai');
                $dia_chi = AZLib::getParam('dia_chi');
                $thanh_pho = AZLib::getParam('thanh_pho');
                $ngay = AZLib::getParam('ngay');
                $time = AZLib::getParam('time');
                $payment_info .= $full_name.",".$dienthoai.",".$dia_chi.",".$thanh_pho.",".$ngay.",".$time;

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);
                $display->add('full_name',$full_name);
                $display->add('dia_chi',$dia_chi);
                $display->add('thanh_pho',  SohaPay::infoForUser($thanh_pho, 'tp'));
                $display->add('ngay',$ngay);
                $display->add('time',  SohaPay::infoForUser($time, 'time'));
                $display->add('service_name', $aryOrderService['type_scs']);
                $display->add('price', number_format($price));
                $display->add('time_exten', $time_exten);

                $content_email=$display->output('payment_online_exten_2',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Gia hạn thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho bang payment scs
                $paymentInfo = array(
                    "order_service_id" => $id,
                    "user_id"        => $user['id'],
                    "user_name"      => $user['user_name'],
                    "payment_types"  => $payment_types,
                    "payment_info"   => $payment_info,
                    "price"          => $price,
                    "payment_status" => 0,
                    "send_mail_stt"  => $send_mail_stt,
                    "reg_exten_stt"  => 1
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);

                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id&exten=1";
                echo $url;
                exit();
            }
        }else if($payment_types == 3){
            global $display;
            
            if($aryOrderService){
                $orderInfo = array(
                    "user_use"              => $user_name,
                    "type_scs"              => $aryOrderService['type_scs'],
                    "date_reg"              => TIME_NOW,
                    "up_count"              => $aryOrderService['up_count'],
                    "cpc_count"             => $aryOrderService['cpc_count'],
                    "item_count"            => $aryOrderService['item_count'],
                    "take_care"             => $aryOrderService['take_care'],
                    "price"                 => $price,
                    "payment_types"         => $payment_types,
                    "time_use"              => $time_exten,
                    "active"                => -3,
                    "reg_exten_stt"         => 1
                );

                //insert
                $id= DB::insert('order_services', $orderInfo);
            }

            if($id){
                $payment_info = "";
                if($user['mobile_phone'] ==""){
                    $phone = $user['home_phone'];
                }else{
                    $phone = $user['mobile_phone'];
                }
                $payment_info .= $user['email'].",".$phone;

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);

                $display->add('service_name', $aryOrderService['type_scs']);
                $display->add('price', number_format($price));
                $display->add('time_exten', $time_exten);

                $content_email=$display->output('payment_online_reg_3',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Gia hạn thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho bang payment scs
                $paymentInfo = array(
                    "order_service_id"  => $id,
                    "user_id"           => $user['id'],
                    "user_name"         => $user['user_name'],
                    "payment_types"     => $payment_types,
                    "payment_info"      => $payment_info,
                    "price"             => $price,
                    "payment_status"    => 0,
                    "send_mail_stt"     => $send_mail_stt,
                    "reg_exten_stt"     => 1
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);

                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id&exten=1";
                echo $url;
                exit();
            }
        }else if($payment_types == 4){
            global $display;

            if($aryOrderService){
                $orderInfo = array(
                    "user_use"              => $user_name,
                    "type_scs"              => $aryOrderService['type_scs'],
                    "date_reg"              => TIME_NOW,
                    "up_count"              => $aryOrderService['up_count'],
                    "cpc_count"             => $aryOrderService['cpc_count'],
                    "item_count"            => $aryOrderService['item_count'],
                    "take_care"             => $aryOrderService['take_care'],
                    "price"                 => $price,
                    "payment_types"         => $payment_types,
                    "time_use"              => $time_exten,
                    "active"                => -3,
                    "reg_exten_stt"         => 1
                );

                //insert
                $id= DB::insert('order_services', $orderInfo);
            }

            if($id){
                $banking_type = Url::get('banking_type');
                $banking_code = SohaPay::listBankCode($banking_type);
                
                $payment_info = "";
                if($user['mobile_phone'] ==""){
                    $phone = $user['home_phone'];
                }else{
                    $phone = $user['mobile_phone'];
                }
                $payment_info .= $user['email'].",".$phone.",".$banking_code;

                //Send email here;
                $display->add('eb_url',WEB_ROOT);
                $display->add('user_id',$user['id']);
                $display->add('user_name',$user['user_name']);

                $display->add('service_name', $aryOrderService['type_scs']);
                $display->add('price', number_format($price));
                $display->add('banking_type', $banking_type);
                $display->add('accNumber', SohaPay::listAccountNumber($banking_code));
                $display->add('banking_name', SohaPay::listBanking($banking_code));
                $display->add('banking_note', SohaPay::listBanking($banking_code, true));
                $display->add('time_exten', $time_exten);

                $content_email=$display->output('payment_online_reg_4',1,'PaymentScs');

                $send_mail_stt = "-1";
                if(System::sendEBEmail($user['email'],'[AzNetGroup] Gia hạn thành công dịch vụ Siêu Chăm Sóc!',$content_email)){
                    $send_mail_stt = "1";
                }

                //tao mang du lieu cho ban payment scs
                $paymentInfo = array(
                    "order_service_id"  => $id,
                    "user_id"           => $user['id'],
                    "user_name"         => $user['user_name'],
                    "payment_types"     => $payment_types,
                    "payment_info"      => $payment_info,
                    "price"             => $price,
                    "payment_status"    => 0,
                    "send_mail_stt"     => $send_mail_stt,
                    "reg_exten_stt"     => 1
                );
                //insert
                DB::insert('payment_scs', $paymentInfo);

                $url = WEB_ROOT."payment_scs.html?cmd=payment_finish&id=$id&exten=1";
                echo $url;
                exit();
            }
        }
    }

    function edit_exten(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}

        $id = (int)Url::get('id',0);
        $time_exten = (int)Url::get('time_exten',0);
        
        $aryOrderService = array();

        if($id){
            $aryOrderService = DB::select("order_services","id = $id AND active = -3 AND reg_exten_stt = 1");
            if($aryOrderService['user_use'] != User::user_name()){
                echo "error";
                exit;
            }else{
                $price = ($aryOrderService['price']/$aryOrderService['time_use'])*$time_exten;
                DB::update('order_services', array("time_use" => $time_exten, "price" => $price), "id=$id");
            }
        }
    }

    function delete_exten(){
        if(!User::is_login()){
			echo "not_login";
			exit();
		}

		if(User::is_block()){
			echo "no_permission";
			exit();
		}

        $id = (int)Url::get('id',0);
        $aryOrderService = array();

        if($id){
            $aryOrderService = DB::select("order_services","id = $id AND active = -3 AND reg_exten_stt = 1");
            if($aryOrderService['user_use'] != User::user_name()){
                echo "error";
                exit;
            }else{
                DB::update('order_services', array("active" => -2), "id=$id");
                DB::update('order_services', array("del_status" => -1), "id=$id");
            }
        }
    }

    function get_user_info_scs(){
        $full_name = Url::get('full_name', '');
        $mobile = Url::get('mobile', '');
        $email = Url::get('email', '');

        if($full_name != '' && $mobile != '' && $email != ''){
            $id = DB::insert('user_wait_takecare', array("full_name" => $full_name, "mobile" => $mobile, "email" => $email, "date_reg" => time()));
        }else{
            echo "input_error";
            exit;
        }
        if($id){
            echo $id;
            exit;
        }else{
            echo "connect_error";
        }
    }
    /*function get_user_info_scs(){
        $full_name = Url::get('full_name', '');
        $mobile = Url::get('mobile', '');
        $email = Url::get('email', '');
        $type = Url::get('type', '');

        if($full_name != '' && $mobile != '' && $email != ''){
            $id = DB::insert('user_wait_takecare', array("full_name" => $full_name, "mobile" => $mobile, "email" => $email, "date_reg" => time(), "type" => $type));
        }else{
            echo "input_error";
            exit;
        }
        if($id){
            echo $id;
            exit;
        }else{
            echo "connect_error";
        }
    }*/
}
?>